package cn.fl.institution.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.institution.vo.PrjNoSignDateVO;
import cn.fl.project.api.IPrjNoSignDateApiService;
import cn.fl.project.api.IPrjNoSignDateService;
import cn.fl.project.condition.PrjNoSignDateQueryCondition;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.dto.PrjNoSignDateInfoDTO;
import cn.fl.project.vo.PrjPrdMtgVO;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 不可签署日期
 * @Author: Fuzq
 * @Date: 17:08 2020-03-04
 * @Version V1.0
 */
@RestController
@RequestMapping(value = "/institution/nosigndate")
public class PrjNoSignDateController {

    @Autowired
    private IPrjNoSignDateApiService prjNoSignDateApiService;

    /**
     * @param
     * @return org.springframework.web.servlet.ModelAndView
     * @description 不可签署日期列表页
     * @author fuzq
     * @date 2020-03-09
     */
    @RequestMapping(value = "/datelistpage.do")
    public ModelAndView get() {
        return new ModelAndView("/project/prjnosigndate/noSignDate");
    }

    /**
     * @param
     * @return org.springframework.web.servlet.ModelAndView
     * @description 不可签署时间列表页
     * @author fuzq
     * @date 2020-03-09
     */
    @RequestMapping(value = "/timelistpage.do")
    public ModelAndView get1() {
        return new ModelAndView("/project/prjnosigndate/noSignTime");
    }

    /**
     * @param
     * @return org.springframework.web.servlet.ModelAndView
     * @description 不可签署日期-新增页
     * @author fuzq
     * @date 2020-03-04
     */
    @RequestMapping(value = "/nosigndateaddpage.do", method = RequestMethod.GET)
    public ModelAndView noSignDateAddPage() {
        ModelAndView modelAndView = null;
        try {
            modelAndView = new ModelAndView("/project/prjnosigndate/noSignDateAdd");
            List<PrjNoSignDateInfoDTO> insList = prjNoSignDateApiService.selectFundInsMap(null);
            modelAndView.addObject("insList", insList);
        } catch (Exception e) {
            BaseLogUtils.newServiceLogger("不可签署日期-新增页异常 , message :" + e).info();
        }
        return modelAndView;
    }

    /**
     * @param
     * @return org.springframework.web.servlet.ModelAndView
     * @description 不可签署日期-编辑页
     * @author fuzq
     * @date 2020-03-04
     */
    @RequestMapping(value = "/nosigndateeditpage.do", method = RequestMethod.GET)
    public ModelAndView noSignDateEditPage(HttpServletRequest request) {
        ModelAndView modelAndView = null;
        try {
            modelAndView = new ModelAndView("/project/prjnosigndate/noSignDateEdit");
            PrjNoSignDateQueryCondition prjNoSignDateQueryCondition = new PrjNoSignDateQueryCondition();
            prjNoSignDateQueryCondition.setId(Long.valueOf(request.getParameter("id")));
            List<PrjNoSignDateInfoDTO> prjNoSignDateInfoDTOS = prjNoSignDateApiService.selectListByCondition(prjNoSignDateQueryCondition);
            if (!CollectionUtils.isEmpty(prjNoSignDateInfoDTOS)) {
                modelAndView.addObject("prjNoSignDateInfoDTO", prjNoSignDateInfoDTOS.get(0));
                modelAndView.addObject("list", prjNoSignDateInfoDTOS.get(0).getNoSignDate());
            }
        } catch (Exception e) {
            BaseLogUtils.newServiceLogger("不可签署日期-编辑页 , message :" + e).info();
        }
        return modelAndView;
    }

    /**
     * @param
     * @return org.springframework.web.servlet.ModelAndView
     * @description 不可签署时间-新增页
     * @author fuzq
     * @date 2020-03-04
     */
    @RequestMapping(value = "/nosigntimeaddpage.do", method = RequestMethod.GET)
    public ModelAndView noSignTimeAddPage() {
        ModelAndView modelAndView = null;
        try {
            modelAndView = new ModelAndView("/project/prjnosigndate/noSignTimeAdd");
            List<PrjNoSignDateInfoDTO> insList = prjNoSignDateApiService.selectFundInsMap(null);
            modelAndView.addObject("insList", insList);
        } catch (Exception e) {
            BaseLogUtils.newServiceLogger("不可签署时间-新增页异常 , message :" + e).info();
        }
        return modelAndView;
    }

    /**
     * @param
     * @return org.springframework.web.servlet.ModelAndView
     * @description 不可签署时间-编辑页
     * @author fuzq
     * @date 2020-03-04
     */
    @RequestMapping(value = "/nosigntimeeditpage.do", method = RequestMethod.GET)
    public ModelAndView noSignTimeEditPage(HttpServletRequest request) {
        ModelAndView modelAndView = null;
        try {
            modelAndView = new ModelAndView("/project/prjnosigndate/noSignTimeEdit");
            Long id = Long.valueOf(request.getParameter("id"));
            PrjNoSignDateQueryCondition prjNoSignDateQueryCondition = new PrjNoSignDateQueryCondition();
            prjNoSignDateQueryCondition.setId(id);
            List<PrjNoSignDateInfoDTO> prjNoSignDateInfoDTOS = prjNoSignDateApiService.selectListByCondition(prjNoSignDateQueryCondition);
            if (CollectionUtils.isNotEmpty(prjNoSignDateInfoDTOS)) {
                PrjNoSignDateInfoDTO prjNoSignDateInfoDTO = prjNoSignDateInfoDTOS.get(0);
                modelAndView.addObject("id", prjNoSignDateInfoDTO.getId());
                modelAndView.addObject("insCode", prjNoSignDateInfoDTO.getInsCode());
                modelAndView.addObject("insName", prjNoSignDateInfoDTO.getInsName());
            }
        } catch (Exception e) {
            BaseLogUtils.newServiceLogger("不可签署时间-编辑页异常 , message :" + e).info();
        }
        return modelAndView;
    }

    /**
     * @param condition
     * @return java.lang.Object
     * @description 不可签署日期-查询列表/模糊查询
     * @author fuzq
     * @date 2020-03-04
     */
    @RequestMapping(value = "/nosigndatelist.do", method = RequestMethod.GET)
    public Object noSignDateListPage(PrjNoSignDateQueryCondition condition, HttpServletRequest request) {
        String pageNum = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        ListPageVO<PrjNoSignDateVO> listPage = new ListPageVO<>();
        if (StringUtils.isNotEmpty(pageNum)) {
            page.setCurrentPage(Integer.parseInt(pageNum));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        page.setCondition(condition);
        try {
            page = prjNoSignDateApiService.selectListPage(page);
            List<PrjNoSignDateInfoDTO> prjNoSignDateInfoDTOS = (List<PrjNoSignDateInfoDTO>) page.getResultList();
            List<PrjNoSignDateVO> prjNoSignDateVOS = new ArrayList<>();
            for (PrjNoSignDateInfoDTO prjNoSignDateInfoDTO : prjNoSignDateInfoDTOS) {
                PrjNoSignDateVO prjNoSignDateVO = new PrjNoSignDateVO();
                BeanUtils.copyProperties(prjNoSignDateInfoDTO, prjNoSignDateVO);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (null != prjNoSignDateInfoDTO.getStartTime() && null != prjNoSignDateInfoDTO.getStartTime()) {
                    String startTime = simpleDateFormat.format(prjNoSignDateInfoDTO.getStartTime());
                    String endTime = simpleDateFormat.format(prjNoSignDateInfoDTO.getEndTime());
                    prjNoSignDateVO.setStartTime(startTime);
                    prjNoSignDateVO.setEndTime(endTime);
                }
                prjNoSignDateVOS.add(prjNoSignDateVO);
            }
            listPage = new ListPageVO<PrjNoSignDateVO>(prjNoSignDateVOS, page.getTotalCount());
        } catch (Exception e) {
            BaseLogUtils.newServiceLogger("不可签署日期-查询列表异常 , message :" + e).info();
        }
        return listPage;
    }

    /**
     * @param prjNoSignDateVO
     * @return cmm.mid.core.framework.page.DataResultVO
     * @description 不可签署时间/不可签署日期  新增/编辑
     * @author fuzq
     * @date 2020-03-12
     */
    @RequestMapping(value = "/updatenosigndate.do", method = RequestMethod.POST)
    public DataResultVO updateNoSignDate(@RequestBody PrjNoSignDateVO prjNoSignDateVO) {
        BaseLogUtils.newLogger("不可签署日期编辑入参:{}", JSON.toJSONString(prjNoSignDateVO)).info();
        DataResultVO dataResultVO = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功");
        if (null != prjNoSignDateVO) {
            boolean insertFlag = prjNoSignDateVO.getInsertFlag();
            PrjNoSignDateInfoDTO prjNoSignDateInfoDTO = new PrjNoSignDateInfoDTO();
            try {
                if (insertFlag) {
                    BaseLogUtils.newLogger("不可签署日期新增操作").info();
                    //有效机构不重复添加
                    if (!uniqueInstructionJudgement(prjNoSignDateVO)) {
                        //校验机构是否重复，重复则不新增
                        dealWithInsertDTO(prjNoSignDateVO, prjNoSignDateInfoDTO);
                        prjNoSignDateApiService.insert(prjNoSignDateInfoDTO);
                    }else {
                        return new DataResultVO(BaseConstant.IS_YESNO_NO, "不能重复添加");
                    }

                } else {
                    BaseLogUtils.newLogger("不可签署日期修改操作").info();
                    dealWithUpdateDTO(prjNoSignDateVO, prjNoSignDateInfoDTO);
                    prjNoSignDateApiService.update(prjNoSignDateInfoDTO);
                }
            } catch (Exception e) {
                BaseLogUtils.newServiceLogger("不可签署时间/不可签署日期 error:").error(LogExceptionEnum.API_CODE_0102, e);
                dataResultVO = new DataResultVO(BaseConstant.IS_YESNO_NO, "操作失败");
            }
        }
        return dataResultVO;
    }

    /**
     * @param prjNoSignDateVO
     * @param prjNoSignDateInfoDTO
     * @return void
     * @description 不可签署时间/日期 新增信息处理
     * @author fuzq
     * @date 2020-03-15
     */
    private void dealWithInsertDTO(PrjNoSignDateVO prjNoSignDateVO, PrjNoSignDateInfoDTO prjNoSignDateInfoDTO) throws Exception {
        List<PrjNoSignDateInfoDTO> prjNoSignDateInfoDTOS = prjNoSignDateApiService.selectFundInsMap(prjNoSignDateVO.getInsId());
        if (CollectionUtils.isEmpty(prjNoSignDateInfoDTOS)) {
            throw new BaseException("当前机构不存在，请检查 insId:" + prjNoSignDateVO.getInsId());
        }
        prjNoSignDateInfoDTO.setInsId(prjNoSignDateInfoDTOS.get(0).getInsId());
        prjNoSignDateInfoDTO.setInsCode(prjNoSignDateInfoDTOS.get(0).getInsCode());
        prjNoSignDateInfoDTO.setInsName(prjNoSignDateInfoDTOS.get(0).getInsName());
        prjNoSignDateInfoDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        prjNoSignDateInfoDTO.setCrtTm(new Date());
        prjNoSignDateInfoDTO.setIsDel(0);
        Date startTime = null;
        Date endTime = null;
        if (null != prjNoSignDateVO.getStartTime() && null != prjNoSignDateVO.getEndTime()) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            startTime = simpleDateFormat.parse(prjNoSignDateVO.getStartTime());
            endTime = simpleDateFormat.parse(prjNoSignDateVO.getEndTime());
            if (startTime.after(endTime)) {
                throw new BaseException("开始时间不能大于结束时间");
            }
        }
        prjNoSignDateInfoDTO.setStartTime(startTime);
        prjNoSignDateInfoDTO.setEndTime(endTime);
    }

    /**
     * @param prjNoSignDateVO
     * @param prjNoSignDateInfoDTO
     * @return void
     * @description 不可签署日期/时间编辑 信息处理
     * @author fuzq
     * @date 2020-03-15
     */
    private void dealWithUpdateDTO(PrjNoSignDateVO prjNoSignDateVO, PrjNoSignDateInfoDTO prjNoSignDateInfoDTO) throws Exception {
        BeanUtils.copyProperties(prjNoSignDateVO, prjNoSignDateInfoDTO);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (null != prjNoSignDateVO.getStartTime() && null != prjNoSignDateVO.getEndTime()) {
            Date startTime = format.parse(prjNoSignDateVO.getStartTime());
            Date endTime = format.parse(prjNoSignDateVO.getEndTime());
            if (startTime.after(endTime)) {
                throw new BaseException("开始时间不能大于结束时间");
            }
            prjNoSignDateInfoDTO.setStartTime(startTime);
            prjNoSignDateInfoDTO.setEndTime(endTime);
        }
        prjNoSignDateInfoDTO.setMdfTm(new Date());
        prjNoSignDateInfoDTO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
    }

    /**
     * @param prjNoSignDateVO
     * @return boolean
     * @description 判断当前机构是否已存在(未作废)
     * @author fuzq
     * @date 2020-03-15
     */
    private boolean uniqueInstructionJudgement(PrjNoSignDateVO prjNoSignDateVO) throws BaseException {
        PrjNoSignDateInfoDTO prjNoSignDateInfoDTO = new PrjNoSignDateInfoDTO();
        BeanUtils.copyProperties(prjNoSignDateVO, prjNoSignDateInfoDTO);
        PrjNoSignDateQueryCondition prjNoSignDateQueryCondition = new PrjNoSignDateQueryCondition();
        prjNoSignDateQueryCondition.setInsId(prjNoSignDateVO.getInsId());
        List<PrjNoSignDateInfoDTO> prjNoSignDateInfoDTOList = prjNoSignDateApiService.selectListByCondition(prjNoSignDateQueryCondition);
        if (CollectionUtils.isNotEmpty(prjNoSignDateInfoDTOList)) {
            return true;
        }
        return false;
    }
}
